﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Collections;
using System.Windows.Forms;
using System.Threading;



namespace TaskManager
{
        ///// <summary>
        ///// 发送登录信息，进行登录
        ///// </summary>
        //private void Login_Click()
        //{
        //    // 设置登录信息
        //    string url = "http://10.80.3.212/zentao/user-login.html";
        //    string postData = "account=test&password=123456&referer=http://10.80.3.212/zentao/my/";

        //    // 发送post信息，进行登录
        //    CookieCollection cookie;
        //    string html = HttpTool.GetHtml(url, postData, Method.POST, out cookie);

        //    if (cookie.Count > 0)
        //    {
        //        MessageBox.Show("您已成功登录！");
        //    }
        //}

        ///// <summary>
        ///// 获取其他页面数据信息(登录成功后,或不需要登录)
        ///// </summary>
        //private void getURL(string url)
        //{
        //    string data = HttpTool.GetHtml(url);   // 实时获取网页数据
        //    MessageBox.Show(data);
        //}

        ///// <summary>
        ///// 登录成功后，在浏览器中打开url
        ///// </summary>
        //private void openURl(string url)
        //{
        //    HttpTool.openUrl(url);
        //    //System.Diagnostics.Process.Start(url); //直接可以访问的网页打开方式
        //}

    public enum Method
    {
        POST = 0,
        GET = 1
    }

    /// <summary>
    /// 用于发送http请求，访问WEB页面
    /// </summary>
    public class HttpTool   //此类参考：http://blog.csdn.net/htsnoopy/article/details/7094224
    {
        #region 设置信息

        public static CookieContainer cookie = new CookieContainer();           // 用于记录访问网页时cookie数据
        public static CookieCollection cookieCollection = new CookieCollection();

        private static string ContentType = "application/x-www-form-urlencoded";
        private static string Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
        private static string UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14";

        public static void setting(string contentType, string accept, string userAgent)
        {
            ContentType = contentType;
            Accept = accept;
            UserAgent = userAgent;
        }

        public static void setting(CookieContainer cc, string contentType, string accept, string userAgent)
        {
            cookie = cc;
            ContentType = contentType;
            Accept = accept;
            UserAgent = userAgent;
        }

        /// <summary>
        /// 清空cookie数据
        /// </summary>
        public static void clearCookie()
        {
            cookie = new CookieContainer();
        }

        #endregion


        #region 网页数据获取的获取

        /// <summary>
        /// 获取指定的网页数据（不需要登录，可以直接访问的页面；或已登录）
        /// </summary>
        public static string GetHtml(string url)
        {
            String data = "";
            try 
            { 
                data = GetHtml(url, out cookieCollection); 
            }
            catch (Exception ex) { }
            return data;
        }

        public static string GetHtml2(string url, Encoding encoding = null)
        {
            try
            {
                WebClient client = new WebClient();

                client.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
                Byte[] pageData = client.DownloadData(url);            //从指定网站下载数据
                if (encoding == null) encoding = Encoding.UTF8;
                string pageHtml = encoding.GetString(pageData);        //如果获取网站页面采用的是GB2312，则使用这句   
                //string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8，则使用这句

                return pageHtml;
            }
            catch (WebException  ex) 
            { 
                return ""; 
            }

        }

        /// <summary>
        /// post数据到指定的网址，获取返回页
        /// </summary>
        public static string GetHtml(string url, string postData)
        {
            // 保存原有的数据信息
            CookieContainer tmp_cookie = cookie;
            CookieCollection tmp_cookieCollection = cookieCollection;
            cookie = new CookieContainer();           // 生成新的cookie

            String html = GetHtml(url);               // 先获取网页信息

            // POST获取数据
            String data = GetHtml(url, postData, Method.POST, out cookieCollection);

            // 还原保存的信息
            cookie = tmp_cookie;
            cookieCollection = tmp_cookieCollection;

            return data;
        }

        /// <summary>
        /// 获取指定的网页数据（不需要登录，可以直接访问的页面）
        /// </summary>
        public static string GetHtml(string url, out CookieCollection cookieCollection)
        {
            try
            {
                HttpWebRequest httpWebRequest;

                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                httpWebRequest.CookieContainer = cookie;

                HttpWebResponse httpWebResponse;
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();

                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                string html = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();

                cookieCollection = cookie.GetCookies(new Uri(url));

                return html;
            }
            catch (Exception)
            {
                cookieCollection = null;
                return null;
            }
        }
        #endregion


        #region 需要验证帐号信息的网页，数据获取

        /// <summary>
        /// post数据到指定的网址，获取cookie数据，和返回页
        /// </summary>
        public static string GetHtml(string url, string postData, Method method, byte[] AppendData=null)
        {
            return GetHtml(url, postData, method, out cookieCollection, AppendData);
        }

        /// <summary>
        /// 将字节数组进行合并
        /// </summary>
        public static byte[] Add(byte[] A1, byte[] A2)
        {
            if (A1 == null) return A2;
            if (A2 == null) return A1;


            // 复制A1,A2到B中
            byte[] B = new byte[A1.Length + A2.Length];

            int j=0;
            for (int i = 0; i < A1.Length; i++) B[j++] = A1[i];
            for (int i = 0; i < A2.Length; i++) B[j++] = A2[i];

            return B;
        }

        /// <summary>
        /// post数据到指定的网址，获取cookie数据，和返回页, AppendData为postData中附加的byte[]数据
        /// </summary>
        public static string GetHtml(string url, string postData, Method method, out CookieCollection cookieCollection, byte[] AppendData = null)
        {
            try
            {
                if (string.IsNullOrEmpty(postData))
                {
                    return GetHtml(url, out cookieCollection);
                }

                byte[] byteRequest = Encoding.Default.GetBytes(postData);
                if (AppendData != null) byteRequest = Add(byteRequest, AppendData);

                HttpWebRequest httpWebRequest;
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);

                httpWebRequest.CookieContainer = cookie;
                httpWebRequest.ContentType = ContentType;

                httpWebRequest.Referer = url;
                httpWebRequest.Accept = Accept;
                httpWebRequest.UserAgent = UserAgent;
                httpWebRequest.Method = method == Method.POST ? "POST" : "GET";
                httpWebRequest.ContentLength = byteRequest.Length;

                Stream stream = httpWebRequest.GetRequestStream();
                stream.Write(byteRequest, 0, byteRequest.Length);
                stream.Close();

                HttpWebResponse httpWebResponse;
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                string html = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();

                cookieCollection = cookie.GetCookies(new Uri(url));

                return html;
            }
            catch (Exception ex)
            {
                cookieCollection = null;
                MessageBox.Show("HttpTool.GetHtml()运行异常：\r\n" + ex.ToString());

                return "";
            }
        }


        /// <summary>
        /// 登录成功后，在浏览器中打开指定的url = http://SERVER/index.php?m=my&f=attendance
        /// </summary>
        public static void openUrl(string server, string url)
        {
            string Url = url.Replace("SERVER", server); // 替换为对应的url地址
            openUrl_Process(cookieCollection, Url);
        }

        /// <summary>
        /// 登录成功后，在浏览器中打开指定的url
        /// </summary>
        public static void openUrl(string url, bool autoRelogin = true, String failStr = "user-login-L215LWRhaWx5Lmh0bWw=.html")
        {
            string html = "";
            if (autoRelogin) html = HttpTool.GetHtml(url);
            if (html.Contains(failStr) && autoRelogin)  // 若登录失败，则自动重新登录，并在登录后再次打开网页
                loginForm.Instance.relogin(url);
            else openUrl_Process(cookieCollection, url);
        }

        public static void openUrl_Process(CookieCollection cookieCollection, string url)
        {
            string tmp = "";

            if (cookieCollection != null)
            {
                try
                {
                    for (int i = 0; i < cookieCollection.Count; i++)
                    {
                        Cookie c = cookieCollection[i];
                        tmp += (tmp.Equals("") ? "" : "&") + c.Name.ToString() + "=" + c.Value.ToString();
                    }
                }
                catch (Exception ex) { }
            }

            //if (url.Contains("?")) Process.Start(url + "&" + tmp);
            //else Process.Start(url + "?" + tmp);
            try
            {
                if (loginForm.settings.useIE_explore.Equals("1")) Process.Start("iexplore.exe", url + "?" + tmp);    
                else Process.Start(url + (tmp.Equals("") ? "" : "?") + tmp);
            }
            catch (Exception ex)        // 若未找到浏览器，则使用IE打开
            {
                Process.Start("iexplore.exe", url + (tmp.Equals("") ? "" : "?") + tmp);

                // 保存使用IE打开的配置信息
                loginForm.settings.useIE_explore = "1";
                loginForm.saveSetttingData();
            }    

            //if (loginForm.settings.useIE_explore.Equals("1")) Process.Start("iexplore.exe", url + "?" + tmp);    
            //else Process.Start(url + "?" + tmp);

            //if (url.Contains("?"))
            //{
            //    Thread.Sleep(1000);   // 延时0.5秒
            //    Process.Start(url);   // url中有通配符？则再次打开
            //}

            //Process.Start(url, tmp);
        }

        #endregion


    }
}
